﻿using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Corina.DataContext.Service
{
    public class WeburlService : ServiceBase
    {
        public List<WeburlInfo> GetFetchedUrl(string connectionString, int roleOrLevelId, PlatformTypeValue platform, AccountTypeValue accountType, params int[] topurlId)
        {
            List<SqlParameter> paras = new List<SqlParameter>();

            paras.Add(new SqlParameter("@Platform", (int)platform));
            paras.Add(new SqlParameter("@RoleOrLevel", roleOrLevelId));
            paras.Add(new SqlParameter("@AccountType", (int)accountType));

            StringBuilder builder = new StringBuilder();
            builder.Append("SELECT tw.* FROM t_weburl AS tw ");
            builder.Append("LEFT JOIN t_weburl_top AS twt ON twt.Id = tw.TopurlId ");
            builder.Append("WHERE 1=1 AND twt.PlatformType = @Platform ");
            builder.Append("AND (tw.ShowToAll=1 OR tw.Id IN (SELECT twp.UrlId FROM t_weburl_permission AS twp WHERE twp.RoleOrLevelId = @RoleOrLevel AND twp.AccountType = @AccountType)) ");
            if (topurlId.Length > 0)
            {
                builder.Append(" AND tw.TopurlId IN (@TopId) ");
                paras.Add(new SqlParameter("@TopId", string.Join(",", topurlId)));
            }

            return DbOperator.GetEntities<WeburlInfo>(connectionString, builder.ToString(), paras.ToArray());
        }

        public List<WeburlInfo> GetAllWeburl(string connectionString, string title, params PlatformTypeValue[] platforms)
        {
            List<SqlParameter> paras = new List<SqlParameter>();

            StringBuilder builder = new StringBuilder();
            builder.Append("SELECT tw.* FROM t_weburl AS tw ");
            builder.Append("LEFT JOIN t_weburl_top AS twt ON twt.Id = tw.TopurlId ");
            builder.Append("WHERE 1=1 ");
            if (platforms.Length > 0)
            {
                builder.Append(" AND twt.PlatformType = @Platform ");
                //int[] ids = platforms.OfType<int>().ToArray();
                paras.Add(new SqlParameter("@Platform", (int)platforms[0]));
            }
            builder.Append("AND tw.Title LIKE @Title");
            paras.Add(new SqlParameter("@Title", string.Format("%{0}%", title)));

            return DbOperator.GetEntities<WeburlInfo>(connectionString, builder.ToString(), paras.ToArray());
        }

        public bool Update(string connectionString, WeburlInfo entity, EntityOperation operation)
        {
            return DbOperator.UpdateEntity(connectionString, entity, operation);
        }
    }
}
